package cj.web.admin.controllers;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.MD5Security;
import cj.utils.ReturnUUID;
import cj.web.admin.dao.AreaDAO;
import cj.web.admin.dao.GameDAO;
import cj.web.admin.dao.GameOrderDAO;
import cj.web.admin.dao.GradeDAO;
import cj.web.admin.dao.PermitDAO;
import cj.web.admin.dao.SchoolDAO;
import cj.web.admin.domain.Area;
import cj.web.admin.domain.Game;
import cj.web.admin.domain.GameOrder;
import cj.web.admin.domain.Grade;
import cj.web.admin.util.SendWXTemplate;
import cj.web.constants.MemuEnum;
import cj.web.constants.OrderSourceEnum;
import cj.web.constants.PayStatusEnum;
import cj.web.constants.PayWayEnum;
import cj.web.constants.PermitStatusEnum;
import cj.web.login.controllers.BaseController;
import cj.web.sc.dao.MemberDAO;
import cj.web.sc.domain.Member;

@Path("/gameOrder")
public class GameOrderController extends BaseController{

	private static Logger logger = Logger.getLogger(GameOrderController.class.getName());
	
	@Autowired
	private GameOrderDAO gameOrderDao;
	@Autowired
	private GradeDAO gradeDao;
	@Autowired
	private AreaDAO areaDao;
	@Autowired
	private SchoolDAO schoolDao;
	@Autowired
	private GameDAO gameDao;
	@Autowired
	private PermitDAO permitDao;
	@Autowired
	private MemberDAO memberDao;
	
	private final static String TEMPLATE_ID ="3eafgX5GTKCKJatSfhb9--Cnoms-o_cvcJtOr4BLLsQ";

	private int beginIndex;
	
	@Get("show")
	public String show(Model model,GameOrder gameOrder) {
		List<Map> grades = gradeDao.asGradeEnum();
		model.add("Grade", grades);
		List<Map> areas = areaDao.asAreaEnum();
		model.add("Area", areas);
		List<Map> schools = schoolDao.asSchoolEnum();
		model.add("School", schools);
		model.add("PayStatus", EnumSet.allOf(PayStatusEnum.class));
		//MemuEnum
        model.add("MemuEnum",MemuEnum.csxsgl);
        List<Game> objs = gameDao.queryAll();
		model.add("gameObjs", objs);
		return "/views/game/gameOrderList.vm";
	}
	
	/**
	 * 参赛选手信息修改页面
	 * @param model
	 * @param gameOrder
	 * @return
	 */
	@Get("updateShow")
	public String updateShow(Model model,GameOrder gameOrder) {
		List<Map> grades = gradeDao.asGradeEnum();
		model.add("Grade", grades);
		List<Map> areas = areaDao.asAreaEnum();
		model.add("Area", areas);
		List<Map> schools = schoolDao.asSchoolEnum();
		model.add("School", schools);
		model.add("PayStatus", EnumSet.allOf(PayStatusEnum.class));
		//MemuEnum
        model.add("MemuEnum",MemuEnum.csxsxggl);
        List<Game> objs = gameDao.queryAll();
		model.add("gameObjs", objs);
		return "/views/game/gameOrderUpList.vm";
	}

	@Post("getList")
	public String queryList(GameOrder gameOrder) {
		JSONObject jo = new JSONObject();
		
		List<GameOrder> objs = gameOrderDao.query(gameOrder);
		
		for(GameOrder obj:objs){
			obj.setPayWayName(obj.getPayWay()!=null?PayWayEnum.getName(obj.getPayWay()):"");
			obj.setStatusName(PayStatusEnum.getName(obj.getStatus()));
		}
		
		int size = gameOrderDao.querysize(gameOrder);
		jo.put("data", objs);
		jo.put("draw", gameOrder.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		List<Map> games = gameDao.asGameEnum();
		model.add("Game", games);
		List<Map> areas = areaDao.asAreaEnum();
		model.add("Area", areas);
		List<Map> grades = gradeDao.asGradeEnum();
		model.add("Grade", grades);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.csxsgl);
		return "/views/game/gameOrderDetail.vm";
	}
	
	@Post("create")
	public String create(GameOrder gameOrder, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		//验证身份信息
		List<Map> hasIdCards = gameOrderDao.getIDCard(gameOrder.getIdentityCard());
		if( hasIdCards != null && hasIdCards.size() > 0 ){                 //该身份证已报名
			Map idCard = hasIdCards.get(0);
			int status = Integer.parseInt(idCard.get("status").toString());
			if( status == PayStatusEnum.WFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_3);   //该身份证已报名,未付费,请前往个人中心>我的报名支付
				return "@" + jo.toString();
			}
			else if ( status == PayStatusEnum.YFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat); //该身份证已付费,已报名,不要重复报名
				return "@" + jo.toString();
			}
		}
		
		//验证参赛证号
		List<Map> permits = permitDao.getValidatePermitById(gameOrder.getPermitId().intValue());   
		if( permits != null && permits.size() > 0 ){
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase); //准考证已使用
			return "@" + jo.toString();
		}
		
		Grade grade = gradeDao.queryById(Integer.parseInt(gameOrder.getGrade()));
		gameOrder.setGrade(grade.getName());
		Area area = areaDao.queryById(Integer.parseInt(gameOrder.getArea()));
		gameOrder.setArea(area.getName());
		
		//参赛证号
		String code = gameOrder.getCode();
		
		gameOrder.setOrderNo(ReturnUUID.getOrderNo(code));
		gameOrder.setUserId(-1);
		gameOrder.setStatus(PayStatusEnum.YFK.getValue());
		gameOrder.setPayWay(PayWayEnum.XCJF.getValue());
		gameOrder.setSource(OrderSourceEnum.XCBM.getValue());
		String account = returnSessionObj(request).getAccount();
		gameOrder.setCreateUser(account);
		gameOrder.setUpdateUser(account);
		gameOrderDao.create(gameOrder);
		
		//更新准考证为已使用
		permitDao.changeStatusById(gameOrder.getPermitId().intValue(), PermitStatusEnum.YXYSY.getValue(),account);
		
		return "@" + jo.toString();
	}
	
	private String beginSubStr(String pattern, String endString){
		int endIndex = pattern.indexOf(endString);
		if(endIndex >= 0){
			pattern = pattern.substring(0,endIndex);
		}
		
		return pattern;
	}
	
	@Get("edit")
	public String edit(Model model, @Param("id")int id){
		GameOrder gameOrder = gameOrderDao.queryById(id);
		model.add("Obj", gameOrder);
		Game game = gameDao.queryById(gameOrder.getGameId().intValue());
		model.add("Game", game);
		List<Map> areas = areaDao.asAreaEnum();
		model.add("Area", areas);
		for(Map area : areas){
			String areaName = area.get("name").toString();
			if( gameOrder.getArea().indexOf(areaName) >= 0){
				model.add("selArea", area.get("id"));
				break;
			}
		}
		
		List<Map> grades = gradeDao.asGradeEnum();
		model.add("Grade", grades);
		for(Map grade : grades){
			String gradeName = grade.get("name").toString();
			if( gameOrder.getGrade().indexOf(gradeName) >= 0){
				model.add("selGrade", grade.get("id"));
				break;
			}
		}
		//MemuEnum
        model.add("MemuEnum",MemuEnum.csxsgl);
		return "/views/game/gameOrderEdit.vm";
	}
	
	@Post("update")
	public String update(GameOrder gameOrder, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		Grade grade = gradeDao.queryById(Integer.parseInt(gameOrder.getGrade()));
		gameOrder.setGrade(grade.getName());
		Area area = areaDao.queryById(Integer.parseInt(gameOrder.getArea()));
		gameOrder.setArea(area.getName());
		String account = returnSessionObj(request).getAccount();
		gameOrder.setUpdateUser(account);
		gameOrderDao.update(gameOrder);
		
		return "@" + jo.toString();
	}
	
	/**
	 * 修改活动订单状态
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("updateStatusById")
	public String updateStatusById(Model model,@Param("id") int id) {
		
		GameOrder obj = gameOrderDao.queryById(id);
		if(obj!=null){
			int status = PayStatusEnum.YFK.getValue();
			int source = OrderSourceEnum.XCBM.getValue();
			int payWay = PayWayEnum.XGDDZT.getValue();
			String payOrder = "000000000";
			gameOrderDao.updateStatusById(id, status, source, payWay, payOrder);
			
			Member memberObj = memberDao.queryById(obj.getUserId());
			String touser = memberObj.getOpenId();
			if(touser!=null && !touser.equals("")){
				//详细内容
				String first ="楚才报名!";
				String orderMoneySum = obj.getPrice().toString();
				//商品信息
				String orderProductName ="楚才竞赛报名!";
				//备注
				String remark ="恭喜（"+obj.getName()+"）同学报名成功！参赛证号："+obj.getCode()+"，请于"+obj.getDuration()+"，到"+obj.getSchoolName()+
						"学校第"+obj.getReturnCode().substring(4, 6)+"号教室"+obj.getReturnCode().substring(6, 9)+"座位参加比赛。";
				try {
					SendWXTemplate.sendWx(touser, TEMPLATE_ID, "", first, orderMoneySum, orderProductName, remark);
				} catch (KeyManagementException | NoSuchAlgorithmException
						| IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return "r:updateShow";
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id) {
		gameOrderDao.deleteById(id);
		return "r:show";
	}
	
	@Post("validatePermit")
	public String validatePermit(@Param("gameId")int gameId, @Param("code")String code, @Param("pwd")String pwd) throws Exception{
		JSONObject jo = new JSONObject();
		
		pwd = MD5Security.md5(pwd);
		List<Map> objs = permitDao.validate(gameId,code,pwd);
		if(objs != null && objs.size() > 0){
			jo.put("returnFlag", Constants.returnObj.returnFlag_true);
			Map obj = objs.get(0);
			String areaName = obj.get("areaName").toString();
			obj.put("areaName", beginSubStr(areaName, "("));
			String schoolName = obj.get("schoolName").toString();
			obj.put("schoolName", beginSubStr(schoolName, "("));
			jo.put("obj", obj);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}
}
